<template>
  <div class="documents-container">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>工作区文档</span>
          <el-button
            type="primary"
            size="small"
            @click="handleRetryFailedDocuments"
            :loading="retrying"
            :disabled="!hasFailedDocuments"
          >
            重试失败文档
          </el-button>
        </div>
      </template>

      <!-- 文档列表 -->
      <el-table :data="documents" style="width: 100%">
        <el-table-column prop="filename" label="文件名称" />
        <el-table-column prop="created_at" label="创建时间">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="embedding_status" label="状态">
          <template #default="scope">
            <el-tag
              :type="getStatusType(scope.row.embedding_status)"
              size="small"
            >
              {{ getStatusText(scope.row.embedding_status) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          :pager-count="7"
          locale="zh-CN"
          prev-text="上一页"
          next-text="下一页"
          total-text="总计"
          size-change-text="条/页"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
          <template #sizes>
            <span style="margin-right: 4px">每页</span>
            <el-select
              v-model="pageSize"
              style="width: 100px"
              @change="handleSizeChange"
            >
              <el-option
                v-for="size in [10, 20, 50, 100]"
                :key="size"
                :value="size"
                :label="`${size}条/页`"
              />
            </el-select>
          </template>
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const props = defineProps({
  workspaceId: {
    type: [String, Number],
    required: true
  }
})

const loading = ref(false)
const retrying = ref(false)
const documents = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 计算是否有失败的文档
const hasFailedDocuments = computed(() => {
  return documents.value.some(doc => doc.embedding_status === 'failed')
})

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    completed: 'success',
    processing: 'warning',
    failed: 'danger',
    pending: 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    completed: '已完成',
    processing: '处理中',
    failed: '失败',
    pending: '等待中'
  }
  return statusMap[status] || '未知'
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取文档列表
const fetchDocuments = async () => {
  try {
    loading.value = true
    const response = await axios.get(
      `/backend/api/llm/workspace/${props.workspaceId}/documents/list/`
    )

    if (response.data) {
      documents.value = response.data
      total.value = response.data.length
    }
  } catch (error) {
    ElMessage.error('获取文档列表失败')
    console.error('获取文档列表错误:', error)
  } finally {
    loading.value = false
  }
}

// 重试失败文档
const handleRetryFailedDocuments = async () => {
  try {
    retrying.value = true
    const response = await axios.post(
      `/backend/api/llm/workspace/${props.workspaceId}/documents/retry/`
    )

    if (response.data && response.data.success) {
      ElMessage.success(`成功重试 ${response.data.retried_count} 个文档`)
      fetchDocuments() // 刷新列表
    }
  } catch (error) {
    ElMessage.error('重试失败文档时出错')
    console.error('重试失败文档错误:', error)
  } finally {
    retrying.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchDocuments()
}

// 处理每页显示数量变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchDocuments()
}

onMounted(() => {
  fetchDocuments()
})
</script>

<style scoped>
.documents-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-pagination) {
  --el-pagination-font-size: 14px;
  --el-text-color-regular: #606266;
}

:deep(.el-input__wrapper) {
  margin: 0 4px;
}
</style>